import { Dialog, throttle } from "quasar";
import { useStore } from "vuex";
import SelectTemplateDialog from "components/dialogs/SelectTemplateDialog.vue";
import { fetchConsumeDetail, fetchMarkBookTepList } from "./fetch";
import SelectAccount from "components/dialogs/SelectAccount.vue";
import ConfirmBiddingDialogVue from "components/dialogs/ConfirmBiddingDialog.vue";

/**
 *
 * @param {string|any[]} cookieValue
 * @returns {{string:string,data:CookieType}}
 */
export function parseCookie(cookieValue) {
  const cookieData = {};
  const cookieArray = [];
  if (typeof cookieValue === "string") {
    cookieValue = cookieValue.split(";");
  }
  cookieValue.forEach((item) => {
    if (typeof item === "string") {
      const match = item.match(/([^\s]+?)=(.+)/);
      if (!match || !match[2]) {
        return;
      }
      item = { name: match[1], value: match[2] };
    }
    if (decodeURIComponent(item.value) !== item.value) {
      item.value = decodeURIComponent(item.value);
    }
    cookieData[item.name] = item.value;
    cookieArray.push(item.name + "=" + encodeURIComponent(item.value));
  });
  return { string: cookieArray.join("; "), data: cookieData };
}

export function cookiesToString(cookies) {
  if (typeof cookies === "string") {
    return cookies;
  }
  const cookieArray = [];
  for (const key in cookies) {
    if (Object.hasOwnProperty.call(cookies, key)) {
      cookieArray.push(key + "=" + encodeURIComponent(cookies[key]));
    }
  }
  return cookieArray.join("; ");
}

const playAudio = throttle(function playAudio(src = "audio/audio-1000.mp3") {
  const tipAudio = new Audio();
  tipAudio.src = src;
  tipAudio.play();
  return tipAudio;
}, 500);
export { playAudio };

export function sleep(millisecond) {
  return new Promise((resolve) => setTimeout(resolve, millisecond));
}

export function refreshDemands() {
  const store = useStore();
  const min = 20;
  const max = 50;
  let timer;
  function refresh(second) {
    clearTimeout(timer);
    timer = setTimeout(async () => {
      const accounts = store.getters["persisted/accounts"];
      refreshMultipleAccounts(store, accounts);
      second = Math.floor(Math.random() * (max - min)) + min;
      console.log(second, "秒后刷新");
      refresh(second);
    }, second * 1000);
  }
  refresh(0);
}

export async function refreshMultipleAccounts(store, accounts) {
  for (let index = 0; index < accounts.length; index++) {
    const account = accounts[index];
    if (account.enable && account.cookie) {
      refreshAccountDemands(store, account.cookie);
      // await refreshAccountDemands(store, account.cookie);
    }
  }
}

export async function refreshAccountDemands(store, cookie) {
  const params = [
    {
      missState: 1,
      pageNum: 1,
      pageSize: 20,
      reqType: 1,
    },
    {
      missState: 1,
      pageNum: 1,
      pageSize: 20,
      reqSource: 1,
      reqType: 2,
    },
    {
      pageNum: 1,
      pageSize: 20,
      reqSource: 1,
      reqType: 3,
    },
  ];

  return new Promise(async (resolve) => {
    for (let index = 0; index < params.length; index++) {
      const param = params[index];
      store.dispatch("common/getOutSourceList", { cookie, param });
      // await store.dispatch("common/getOutSourceList", { cookie, param });
    }
    resolve();
  });
}

export function diffTime(difftime) {
  const seconds = parseInt(difftime % 60);
  const minutes = parseInt((difftime / 60) % 60);
  const hours = parseInt((difftime / 60 / 60) % 24);
  const days = parseInt(difftime / 60 / 60 / 24);
  return { days, hours, minutes, seconds };
}

export function getAvatar(e, t) {
  if (!e) return "http://t4.zbjimg.com/r/p/task/48.gif";
  let n = "000000000" + e;
  let r = n.substr(n.length - 9, 9);
  return (
    (t = "!" + (t || "middle")),
    "https://avatar.zbjimg.com/" +
      r.substr(0, 3) +
      "/" +
      r.substr(3, 2) +
      "/" +
      r.substr(5, 2) +
      "/200x200_avatar_" +
      r.substr(7, 2) +
      ".jpg" +
      t +
      "?t=" +
      Date.now()
  );
}

export function selectAccount() {
  return new Promise((resolve, reject) => {
    Dialog.create({
      component: SelectAccount,
    })
      .onOk(resolve)
      .onCancel(reject);
  });
}

export function getBiddingScheme(categoryId, preFetch) {
  return new Promise(async (resolve, reject) => {
    let template;
    if (preFetch) {
      const tmp = await fetchMarkBookTepList(categoryId).catch(reject);
      if (!tmp) {
        return reject();
      }
      template = tmp.data.tempList;
    }
    Dialog.create({
      component: SelectTemplateDialog,
      componentProps: { template, categoryId },
    }).onDismiss(resolve);
  });
}

export function getBiddingConsume(demandId, preFetch) {
  return new Promise(async (resolve, reject) => {
    let props = { demandId };
    if (preFetch) {
      const res = await fetchConsumeDetail(demandId).catch(reject);
      if (!res) {
        return reject();
      }
      props.consume = res.data.consume;
      props.message = res.data.message;
    }

    Dialog.create({
      component: ConfirmBiddingDialogVue,
      componentProps: props,
    }).onDismiss(resolve);
  });
}

export function isExpire(expires_time) {
  if (expires_time === 0) {
    return false;
  }
  // console.log(expires_time.toString().length);
  return expires_time * 1000 - +new Date() <= 0;
}

export const electronApi = {
  /**
   *
   * @param {String} url
   * @param {{userid:Number,nickname:String}} cookies
   * @param {Electron.BrowserWindowConstructorOptions} options
   * @returns
   */
  openWork: (url, cookies, options) =>
    window.electron.openWork(url, cookies, options),

  /**
   *
   * @param {{username?:String,password?:String}} options
   * @returns
   */
  login: (options) => window.electron.login(options),

  /**
   *
   * @param {Electron.NotificationConstructorOptions} options
   * @param {{demandid?:String,userid?:String}} other
   * @returns {void}
   */
  notify: (options, other) => window.electron.notify(options, other),

  server: (cookies) => window.electron.server(cookies),
};
